package com.hottv.meeting.videomeeting.module.edp;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.chinamobile.iot.onenet.edp.Common;
import com.chinamobile.iot.onenet.edp.toolbox.EdpClient;
import com.chinamobile.iot.onenet.edp.toolbox.Listener;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by chengwenqiang on 2019/6/4.
 */

public class EDPUtils {

    private static final String ETH_ADDRESS_PATH = "/sys/class/net/eth0/address";
    private static String deviceSN = "0293993859438";
    private static String title = "视频会议设备";

    private static String devicesId = "";
    private static String appId = "";

    private static int mConnectType = EdpClient.CONNECT_TYPE_1;
    private static int mEncryptType = Common.Algorithm.NO_ALGORITHM;
    private static long mPingInterval = 10000L;

    public static String edp_devices_Id = "349134130";  //one-net 平台上的账号，唯一标示符号

    public static void bindDevices(final Context context, final Listener listener)
    {

        String deviceId = getWireMacAddress(context);
//        String deviceId = getIMEI(context);
        Log.i(EDPConfig.TAG,"deviceId:"+deviceId);
        EDPControl.getDeviceAndKey(context, deviceId, title, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (response.code() == 200) {
                    String strTemp = response.body().string();
                    Log.i(EDPConfig.TAG,"body:"+strTemp);
                    JsonObject room = new Gson().fromJson(strTemp, JsonObject.class);
                    if(room.get("errno").getAsInt()==0) {
                        Log.v(EDPConfig.TAG, "注册设备成功");
                        final String device_id = room.getAsJsonObject("data").get("device_id").getAsString();
                        edp_devices_Id = device_id;
                        final String appId = room.getAsJsonObject("data").get("key").getAsString();
                        Log.i(EDPConfig.TAG, "device_id:" + device_id + ",appid:" + appId);
                        Looper.prepare();
                        initialize(context, mConnectType, device_id, appId, mPingInterval, mEncryptType, listener);
                        Looper.loop();
                    }else
                    {
                        Log.v(EDPConfig.TAG, "注册设备失败");
                    }
                }
            }
        });
    }

    private static void initialize(Context context, int connectType, String deviceId, String authInfo,
                                                 long pingInterval, int encryptType, Listener listener) {
        // 1、初始化SDK

        EdpClient.initialize(context, connectType, deviceId, authInfo);

        // 2、设置接收响应的回调
        Log.i(EDPConfig.TAG,"setListener");
        EdpClient.getInstance().setListener(listener);
        // 3、设置自动发送心跳的周期（默认4min）
        EdpClient.getInstance().setPingInterval(pingInterval);
        // 4、建立TCP连接
        EdpClient.getInstance().connect();
        if (Common.Algorithm.NO_ALGORITHM == encryptType) {
            // 5、如果使用明文通信，则建立连接后直接发送连接请求
            EdpClient.getInstance().sendConnectReq();
        } else if (Common.Algorithm.ALGORITHM_AES == encryptType) {
            // 6、如果使用加密通信，则先发送加密请求，然后在加密响应回调中发送连接请求
            EdpClient.getInstance().requestEncrypt(Common.Algorithm.ALGORITHM_AES);
        }
    }

    public static String getIMEI(Context context)
    {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();
    }

    public static String getDeviceId(Context context){
        String  deviceId = "";
        if(ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            deviceId = tm.getDeviceId();
        }
        return deviceId;
    }

    //请求权限
    public static boolean checkSelfPermission(Activity activity, String permission, int requestCode) {
//        Log.d(MeetingConfig.TAG,":" + permission + " :" + requestCode);
        if (ContextCompat.checkSelfPermission(activity.getApplicationContext(),
                permission)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(activity,
                    new String[]{permission},
                    requestCode);
            return false;
        }

        return true;
    }

    public static String getWireMacAddress(Context mContext) {
        String macAddress = loadFileAsString(ETH_ADDRESS_PATH);
        if(macAddress == null){
            return "";
        }
        return macAddress;
    }

    public static String loadFileAsString(String filePath){
        try {
            BufferedReader macReader = new BufferedReader(new FileReader(filePath));
            String buffer = null;
            StringBuilder builder = new StringBuilder();
            while((buffer = macReader.readLine()) != null){
                builder.append(buffer);
            }
            return builder.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
